package com.zwps.biz.controller.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwps.biz.api.model.dto.broadcast.BroadcastDTO;
import com.zwps.biz.api.model.dto.broadcast.SBroadcastDTO;
import com.zwps.biz.api.model.vo.strsvrr.RadarDataVO;
import com.zwps.biz.controller.config.OkHttpConfig;
import com.zwps.biz.controller.config.SSLHelper;
import com.zwps.biz.dal.db.object.PrecipitationRadarDataDO;
import com.zwps.biz.domain.service.PrecipitationRadarDataService;
import com.zwps.biz.domain.service.impl.ApiService;
import com.zwps.common.cache.CacheService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@Validated
@RequestMapping("broadcast")
public class BroadcastController {


    @Autowired
    private ApiService apiService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private PrecipitationRadarDataService radarDataService;

    @Autowired
    OkHttpConfig httpConfig;

    @Value(value = "${application.broadcast.filesUrl}")
    private String fileUrl;
    @Value(value = "${application.broadcast.token}")
    private String token;
    @Value(value = "${application.broadcast.baiyiUrl}")
    private String baiyiUrl;


    /**
     * 查询设备
     *
     * @return
     */
    @GetMapping("/device")
    public JSONObject getDevice() {
        return apiService.getDevice();
    }

    /**
     * 查询计划
     *
     * @return
     */
    @GetMapping("/plan")
    public JSONObject getPlan(String deviceId) {
        return apiService.getPlan(deviceId);
    }

    /**
     * 查询音乐
     *
     * @return
     */
    @GetMapping("/file")
    public JSONObject getFile(String deviceId) {
        return apiService.getFile(deviceId);
    }


    /**
     * 创建任务
     *
     * @return
     */
    @PostMapping("/task")
    public String addTask(@RequestBody BroadcastDTO dto) {

        if (ObjectUtils.isEmpty(dto)) {
            dto = new BroadcastDTO();
        }
        return apiService.addTask("task", dto);
    }

    /**
     * 执行实时任我
     *
     * @return
     */
    @PostMapping("/update/task")
    public JSONObject updateTask(@RequestBody SBroadcastDTO dto) {
        List<Integer> idList = new ArrayList<>();
        if (ObjectUtils.isEmpty(dto)) {
            dto = new SBroadcastDTO();
        }
        Integer num;
        try {
            num = Integer.parseInt(cacheService.getValue(dto.getDevice_ids().get(0).toString()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        dto.setDevice_ids(dto.getDevice_ids().stream()
                .map(this::convertItemToInteger)
                .filter(Objects::nonNull) // 过滤掉转换失败的元素
                .collect(Collectors.toList()));

        return JSONObject.parseObject(apiService.updateTask("real_time_task", dto, num));
    }

    private Object convertItemToInteger(Object item) {
        if (item instanceof String) {
            return convertStringToInteger((String) item);
        } else if (item instanceof Integer) {
            return item; // 已经是Integer，直接返回
        }
        // 其他类型可以根据需求处理或返回null
        return null;
    }

    private Integer convertStringToInteger(String str) {
        if (str == null || str.trim().isEmpty()) {
            return null;
        }

        try {
            // 获取下划线前的部分
            String numberStr = str;
            int underscoreIndex = str.indexOf('_');
            if (underscoreIndex > 0) {
                numberStr = str.substring(0, underscoreIndex);
            }

            return Integer.parseInt(numberStr.trim());
        } catch (NumberFormatException e) {
            System.err.println("字符串转换Integer失败: " + str);
            return null;
        }
    }
//   List<Integer> getDeviceIds(){
//       List<Integer> idList = new ArrayList<>();
//       try {
//           String device = getDevice();
//           // 1. 将字符串解析为JSON对象
//           JSONObject jsonObject = JSONObject.parseObject(device);
//           // 2. 检查data字段是否存在且为数组
//           if (!jsonObject.containsKey("data")) {
//               throw new RuntimeException("JSON中缺少data字段");
//           }
//           JSONArray dataArray = jsonObject.getJSONArray("data");
//           // 3. 遍历data数组提取id
//           dataArray.forEach(item -> {
//               JSONObject itemObj = (JSONObject) item;
//               Integer id = itemObj.getInteger("id");
//               if (id != null) {
//                   idList.add(id);
//               }
//           });
//        return idList;
//
//       } catch (Exception e) {
//           throw new RuntimeException("解析JSON失败: " + e.getMessage(), e);
//       }
//    }

    /**
     * 执行任务
     *
     * @param
     * @return
     */
    @GetMapping("/startTask")
    public String startTask(@RequestParam(value = "id", required = false) String id) {
        return apiService.startTask(id);
    }

    /**
     * 停止任务
     *
     * @param id
     * @return
     */
    @GetMapping("/stopTask")
    public String stopTask(@RequestParam(value = "id", required = false) String id) {
        return apiService.stopTask(id);
    }

    /**
     * 设备id
     *
     * @param id
     */
    @GetMapping("/stopSTask")
    public void stopSTask(@RequestParam(value = "id", required = false) String id) {
        List<String> idList = Arrays.asList(id.split(","));
        for (String s : idList) {
            apiService.stopSTask(s);
        }
    }

    @Scheduled(cron = "0 */5 * * * ?")
    @GetMapping("/savetoFile")
    public void savetoFile() {
        List<PrecipitationRadarDataDO> list = new ArrayList<>();
        List<RadarDataVO> list1 = radarDataService.getDate();

//        for (RadarDataVO radarDataVO : list1) {
//            String[] split = radarDataVO.getTime().split(",");
//            String type = radarDataVO.getType();
//            for (String s : split) {
//                System.out.println("type:" + type + ",s:" + s);
//                saveDate(getHistoryFiles(type, s), list);
//            }
//        }
        saveDate(getHistoryFiles("PR", "5min"), list);
        radarDataService.remove(new LambdaQueryWrapper<PrecipitationRadarDataDO>()
                .lt(PrecipitationRadarDataDO::getDateTime, LocalDateTime.now().minusHours(2)));
        radarDataService.saveBatch(list);
    }

    public void saveDate(String historyFiles, List<PrecipitationRadarDataDO> list) {

        JSONObject objects = JSONObject.parseObject(historyFiles);
        JSONArray jsonArray = objects.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            PrecipitationRadarDataDO radarDataDO = new PrecipitationRadarDataDO();
            radarDataDO.setDateTime(jsonArray.getJSONObject(i).getString("fileDate"));
            String fileDate = getDataByFile(jsonArray.getJSONObject(i).getString("fileId"), "1");
            JSONObject jsonObject = JSONObject.parseObject(fileDate);
            radarDataDO.setPngData(jsonObject.getString("png"));
            radarDataDO.setGrid(jsonObject.getString("grid"));
            radarDataDO.setLonRes(jsonObject.getBigDecimal("lonRes"));
            radarDataDO.setSLat(jsonObject.getBigDecimal("sLat"));
            radarDataDO.setLatRes(jsonObject.getBigDecimal("latRes"));
            radarDataDO.setSLon(jsonObject.getBigDecimal("sLon"));
            radarDataDO.setType("PR");
            radarDataDO.setTime_type("5min");
            list.add(radarDataDO);
        }

    }

    /**
     * 查询降水雷达数据
     */
    @GetMapping("/getRadarData")
    public List<PrecipitationRadarDataDO> getRadarData(@RequestParam(value = "startTime",required = false) String startTime, @RequestParam(value = "endTime",required = false) String endTime) {
        LambdaQueryWrapper<PrecipitationRadarDataDO> wrapper = new LambdaQueryWrapper<>();
         // 时间范围条件
        if (startTime != null && endTime != null) {
            wrapper.between(PrecipitationRadarDataDO::getDateTime, startTime, endTime);
        } else {
            // 如果没有时间范围参数，限制返回12条记录
            wrapper.last("LIMIT 12");
        }
         // 始终按时间降序排序
        wrapper.orderByDesc(PrecipitationRadarDataDO::getDateTime);
        return radarDataService.list(wrapper);
    }

    /**
     * 查询产品数据列表
     *
     * @param
     */
    @GetMapping("/getHistoryFiles")
    public String getHistoryFiles(String type,
                                  String ele

    ) {
        String startTime;
        String endTime;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        PrecipitationRadarDataDO dataDO = radarDataService.getOne(
                new LambdaQueryWrapper<PrecipitationRadarDataDO>().orderByDesc(PrecipitationRadarDataDO::getDateTime).last("limit 1")
        );
        if (!ObjectUtils.isEmpty(dataDO)) {

            startTime = dataDO.getDateTime();
            endTime = now.format(formatter);
        } else {
            int sub = 0;
            // 第一次请求
            if ("z".equals(ele) || "5min".equals(ele)) {
                sub = 1;
            }
            if ("1hour".equals(ele) || "3hour".equals(ele) || "rain_1hour".equals(ele) || "rain_2hour".equals(ele)) {
                sub = 12;
            }
            if ("6hour".equals(ele)) {
                sub = 24;
            }
            startTime = now.minusHours(sub).format(formatter);
            endTime = now.format(formatter);
        }
        // 定义时间格式化器


        // 构建请求URL
        HttpUrl url = HttpUrl.parse(fileUrl + "/getHistoryFiles")
                .newBuilder()
                .addQueryParameter("startTime", startTime)
                .addQueryParameter("endTime", endTime)
                .addQueryParameter("type", type)
                .addQueryParameter("ele", ele)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = httpConfig.okHttpClient().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code());
            }

            // 解析响应数据
            String responseBody = response.body().string();
            System.out.println("请求成功: " + responseBody);

            // 返回响应数据
            return responseBody;

        } catch (IOException e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }


    public String getDataByFile(String fileId,
                                String dataType) {

        // 构建请求URL
        HttpUrl url = HttpUrl.parse(fileUrl + "/getDataByFile")
                .newBuilder()
                .addQueryParameter("fileId", fileId)
                .addQueryParameter("dataType", dataType)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try (Response response = httpConfig.okHttpClient().newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code());
            }

            // 解析响应数据
            String responseBody = response.body().string();
            System.out.println("请求成功: " + responseBody);
            // 返回响应数据
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    @GetMapping("/getCurrentData")
    public ResponseEntity<?> getCurrentData(@RequestParam(value = "current", defaultValue = "1") Integer current,
                                            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        try {
            // 构建请求体
            Map<String, Object> requestBodyMap = new HashMap<>();
            requestBodyMap.put("current", current);
            requestBodyMap.put("size", size);
            requestBodyMap.put("token", token);
            String requestBody = new ObjectMapper().writeValueAsString(requestBodyMap);

            Request request = new Request.Builder()
                    .url(baiyiUrl)
                    .post(okhttp3.RequestBody.create(requestBody, MediaType.parse("application/json")))
                    .build();

            try (Response response = httpConfig.okHttpClient().newCall(request).execute()) {
                String responseBody = null;
                String resp = response.body().string();
                if (response.isSuccessful() && !ObjectUtils.isEmpty(JSONObject.parseObject(resp).getJSONObject("data"))) {
                    responseBody = resp;
                    cacheService.setValue("currentData", responseBody);
                } else {
                    responseBody = cacheService.getValue("currentData");
                }

                return ResponseEntity.ok()
                        .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                        .body(responseBody);
            }

        } catch (IOException e) {
            try {
                String cachedData = cacheService.getValue("currentData");
                if (cachedData != null && !cachedData.trim().isEmpty()) {
                    return ResponseEntity.ok()
                            .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                            .body(cachedData);
                }
            } catch (Exception cacheEx) {
                e.printStackTrace();
            }
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "服务暂时不可用，请稍后重试");
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}
